package com.xul.yygh.msm.controller;

import com.xul.yygh.common.result.Result;
import com.xul.yygh.msm.service.MsmService;
import com.xul.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author xul
 * @create 2021-07-14 20:47
 */

@Api(tags = "短信服务接口")
@RestController
@RequestMapping("api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @ApiOperation("发送短信验证码")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        // 从redis中取验证码 如果取到验证码就返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 生成验证码
        code = RandomUtil.getSixBitRandom();
        // 如果取不到验证码就生成验证码 调用service方法，通过整合短信服务进行发送
        boolean isSend = msmService.send(phone, code);
        // 生成验证码放到redis里面，设置有效时间
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            // 发送验证码失败
            return Result.fail().message("发送短信失败");
        }
    }
}
